<!-- 出库单修改界面 -->
<template>
    <!--基本信息-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">基础信息</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-form :model="outstockform" :rules="rules" ref="outstockref" style="margin-top: 20px;margin-left: 50px;" label-width="auto">
            <el-row>
                <el-col :span="11">
                    <el-form-item label="出库单号" prop="code">
                        <el-input placeholder="自动获取系统编号" style="width: 300px;" v-model="outstockform.code" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="出库类型" prop="type">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="outstockform.type" disabled>
                            <el-option v-for="item in types" :key="item.bus_id" :label="item.bus_name" :value="item.bus_name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 动态表单部分 -->
            <!-- 销售出库 -->
            <div v-if="outstockform.type === '销售出库'">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whid">
                            <el-select placeholder="请选择" style="width: 300px;" v-model="outstockform.whid">
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                            <el-button type="success" text @click="setWarehouse">设置</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="出库日期" prop="date">
                            <el-date-picker v-model="outstockform.date" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="outorder">
                            <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="outstockform.outorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="客户名称" prop="custname">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="outstockform.custname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="收货人" prop="linkman">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="outstockform.linkman" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="联系方式" prop="linkphone">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="outstockform.linkphone" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 采购退货 -->
            <div v-if="outstockform.type === '退货出库'">
                 <el-row>
                    <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whid">
                            <el-select placeholder="请选择" style="width: 300px;" v-model="outstockform.whid">
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                             <el-button type="success" text @click="setWarehouse">设置</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="出库日期" prop="date">
                            <el-date-picker v-model="outstockform.date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="outorder">
                            <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="outstockform.outorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="供应商" prop="supname">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="outstockform.supname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="收货人" prop="linkman">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="outstockform.linkman"></el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="11">
                        <el-form-item label="联系方式" prop="linkphone">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="outstockform.linkphone"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 调拨出库 -->
            <div v-if="outstockform.type === '调拨出库'">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="outorder">
                           <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="outstockform.outorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                         <el-form-item label="仓库名称" prop="whname">
                            <el-input placeholder="请输入" style="width: 300px;" v-model="outstockform.whname" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                     <el-col :span="11">
                        <el-form-item label="出库日期" prop="date">
                            <el-date-picker v-model="outstockform.date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 盘亏出库 -->
            <div v-if="outstockform.type === '盘亏出库'">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="仓库名称" prop="whid">
                            <el-select 
                                placeholder="请选择" 
                                style="width: 300px;" 
                                v-model="outstockform.whid"
                                disabled
                            >
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                            <el-button type="success" text @click="setWarehouse">设置</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="出库日期" prop="date">
                            <el-date-picker v-model="outstockform.date" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 300px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="关联单号" prop="outorder">
                            <el-input placeholder="请选择关联单号" style="width: 300px;" v-model="outstockform.outorder" readonly>
                                <template #append>
                                    <el-button @click="openOrderDialog">...</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>


            <!-- 公共字段 -->
            <el-row>
                <el-col :span="11">
                    <el-form-item label="经办人" prop="outuser">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="outstockform.outuser">
                            <el-option v-for="item in users" :key="item.user_id" :label="item.user_name" :value="item.user_name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" placeholder="请输入" v-model="outstockform.remark"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>

    <!-- 出库明细 -->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">出库明细</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <div style="text-align: left;margin-left: 20px;">
            <el-button type="success" @click="ShowProduct">添加</el-button>
            <el-button @click="batchRemoveProducts">移除</el-button>
        </div>

        <!-- 销售出库明细 -->
        <div v-if="outstockform.type === '销售出库'">
            <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                 <el-table-column fixed type="selection" width="55"></el-table-column>
                 <el-table-column fixed type="index" label="序号" width="60"></el-table-column>
                 <el-table-column fixed prop="proc_name" label="货品名称" width="120"></el-table-column>
                 <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
                 <el-table-column prop="type_name" label="货品类型"></el-table-column>
                 <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
                 <el-table-column prop="proc_model" label="规格型号"></el-table-column>
                 <el-table-column prop="proc_inventory" label="当前库存"></el-table-column>
                 <el-table-column prop="proc_saled_num" label="销售数量"></el-table-column>
                 <el-table-column label="已出库数量" width="120">
                    <template #default="scope">
                        {{ (scope.row.saled_outstockOK_num || 0) + (scope.row.outd_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="未出库数量" width="120">
                    <template #default="scope">
                        {{ (scope.row.proc_saled_num || 0) - (scope.row.saled_outstockOK_num || 0) - (scope.row.outd_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="出库库位" width="150">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 120px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                 <el-table-column label="本次出库数量" width="200px">
                      <template #default="scope">
                         <el-input-number v-model="scope.row.outd_num" :min="1" :max="scope.row.proc_saled_num - scope.row.saled_outstockOK_num"></el-input-number>
                      </template>
                 </el-table-column>
                 <el-table-column label="销售单价" prop="proc_saled_price" width="120"></el-table-column>
                 <el-table-column label="销售金额" prop="proc_saled_total" width="120"></el-table-column>
                 <el-table-column label="出库金额" prop="outd_total" width="120">
                    <template #default="scope">
                        {{ (scope.row.outd_num * scope.row.proc_saled_price || 0).toFixed(2) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="生产日期" prop="proc_date" width="150">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.proc_date" type="date" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" style="width: 120px;"></el-date-picker>
                    </template>
                 </el-table-column>
                 <el-table-column label="备注" prop="remark" width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 120px;"></el-input>
                    </template>
                 </el-table-column>
                 <el-table-column label="操作" width="80" fixed="right">
                      <template #default="scope">
                          <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                      </template>
                 </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                 <span style="margin-right: 15px;">未出库数量: <b style="color: red;">{{ sumNotInstockNum }}</b></span>
                 <span style="margin-right: 15px;">已出库数量: <b style="color: red;">{{ sumAlreadyInstockNum }}</b></span>
                 <span style="margin-right: 15px;">出库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">出库数量: <b style="color: red;">{{ sumOutstockNum }}</b></span>
                 <span>出库金额: <b style="color: red;">{{ sumOutstockAmount }}</b></span>
            </div>
        </div>

         <!-- 退货出库明细 -->
         <div v-if="outstockform.type === '退货出库'">
             <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                <el-table-column fixed type="selection"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="60"></el-table-column>
                <el-table-column fixed prop="proc_name" label="货品名称" width="120"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
                <el-table-column prop="type_name" label="货品类型" width="120"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="120"></el-table-column>
                <el-table-column prop="proc_inventory" label="当前库存" width="120"></el-table-column>
                <el-table-column prop="purtd_num" label="退货数量" width="120"></el-table-column>
                <el-table-column prop="purtd_outstockOK_num" label="已出库数量" width="150"></el-table-column>
                <el-table-column prop="purtd_outstockNO_num" label="未出库数量" width="150"></el-table-column>
                <el-table-column label="出库库位" width="150">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 120px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                <el-table-column label="本次出库数量"  width="200px">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.outd_num" :min="1" :max="(scope.row.purtd_num || 0) - (scope.row.purtd_outstockOK_num || 0)"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="purtd_price" label="退货单价" width="120"></el-table-column>
                <el-table-column prop="purtd_total" label="退货金额" width="120"></el-table-column>
                <el-table-column label="出库金额" prop="outd_total" width="120">
                    <template #default="scope">
                        {{ (scope.row.outd_num * scope.row.purtd_price || 0).toFixed(2) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="备注" prop="remark" width="200">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 120px;"></el-input>
                    </template>
                 </el-table-column>
                <el-table-column label="操作" fixed="right">
                    <template #default="scope">
                        <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                <span style="margin-right: 15px;">未出库数量: <b style="color: red;">{{ sumNotInstockNum }}</b></span>
                 <span style="margin-right: 15px;">已出库数量: <b style="color: red;">{{ sumAlreadyInstockNum }}</b></span>
                 <span style="margin-right: 15px;">出库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">出库数量: <b style="color: red;">{{ sumOutstockNum }}</b></span>
                 <span>出库金额: <b style="color: red;">{{ sumOutstockAmount }}</b></span>
            </div>
        </div>

        <!-- 调拨出库明细 -->
        <div v-if="outstockform.type === '调拨出库'">
            <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                 <el-table-column fixed type="selection"></el-table-column>
                 <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                 <el-table-column fixed prop="proc_name" label="货品名称" width="150"></el-table-column>
                 <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                 <el-table-column prop="type_name" label="货品类型" width="150"></el-table-column>
                 <el-table-column prop="proc_model" label="规格型号" width="150"></el-table-column>
                 <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
                 <el-table-column prop="proc_inventory" label="当前库存"></el-table-column>
                 <el-table-column label="出库库位" width="150">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 120px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                 <el-table-column prop="ald_num" label="调拨数量"></el-table-column>
                 <el-table-column prop="ald_outOK_num" label="已出库数量" width="150">
                     <template #default="scope">
                        {{ (scope.row.ald_outOK_num || 0) + (scope.row.outd_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="未出库数量" width="150">
                     <template #default="scope">
                        {{ (scope.row.ald_num || 0) - (scope.row.ald_outOK_num || 0) - (scope.row.outd_num || 0) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="本次出库数量" width="200px">
                      <template #default="scope">
                         <el-input-number v-model="scope.row.outd_num" :min="0" :max="(scope.row.ald_num || 0) - (scope.row.ald_outOK_num || 0)"></el-input-number>
                      </template>
                 </el-table-column>
                 <el-table-column prop="ald_price" label="出库单价" width="150">
                    <template #default="scope">
                         {{ (scope.row.ald_price || 0).toFixed(2) }}
                    </template>
                 </el-table-column>
                 <el-table-column prop="outd_total" label="出库金额" width="150">
                    <template #default="scope">
                        {{ ((scope.row.outd_num || 0) * (scope.row.ald_price || 0)).toFixed(2) }}
                    </template>
                 </el-table-column>
                 <el-table-column label="备注" prop="remark" width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 120px;"></el-input>
                    </template>
                 </el-table-column>
                <el-table-column label="操作" width="80" fixed="right">
                      <template #default="scope">
                          <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                      </template>
                 </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                 <span style="margin-right: 15px;">出库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">出库数量: <b style="color: red;">{{ sumOutstockNum }}</b></span>
                 <span>出库金额: <b style="color: red;">{{ sumOutstockAmount }}</b></span>
            </div>
        </div>

        <!-- 盘亏出库明细 -->
        <div v-if="outstockform.type === '盘亏出库'">
            <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
                <el-table-column fixed type="selection"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                <el-table-column fixed prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="type_name" label="货品类型" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="150"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
                <el-table-column prop="proc_inventory" label="当前库存" width="150"></el-table-column>
                <el-table-column label="出库库位" width="150">
                      <template #default="scope">
                         <el-select v-model="scope.row.slot_id" placeholder="请选择" style="width: 120px;">
                             <el-option v-for="loc in slots" :key="loc.slot_id" :label="loc.slot_name" :value="loc.slot_id"></el-option>
                         </el-select>
                      </template>
                 </el-table-column>
                  <el-table-column label="出库数量" width="220">
                     <template #default="scope">
                         <el-input-number 
                             v-model="scope.row.outd_num" 
                             :min="Math.abs(scope.row.profitandloss_num)"
                             :max="Math.abs(scope.row.profitandloss_num)"
                             :placeholder="`最大${Math.abs(scope.row.profitandloss_num)}`">
                         </el-input-number>
                     </template>
                </el-table-column>
                <el-table-column prop="outd_price" label="出库单价" width="220">
                    <template #default="scope">
                        <el-input-number 
                            v-model="scope.row.outd_price" 
                            :min="scope.row.icd_price"
                            :placeholder="`参考${scope.row.icd_price}`">
                        </el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="出库金额" width="150">
                     <template #default="scope">
                        {{ (scope.row.outd_num * scope.row.outd_price || 0).toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right">
                     <template #default="scope">
                         <el-button type="danger" size="small" text @click="removeProduct(scope.row.proc_id)">移除</el-button>
                     </template>
                </el-table-column>
            </el-table>
            <div style="text-align: right; margin-top: 10px; padding: 10px 20px; border-top: 1px solid #e6e6e6;">
                 <span style="margin-right: 15px;">出库种类: <b style="color: red;">{{ selectedProducts.length }}</b></span>
                 <span style="margin-right: 15px;">出库数量: <b style="color: red;">{{ sumOutstockNum }}</b></span>
                 <span>出库金额: <b style="color: red;">{{ sumOutstockAmount }}</b></span>
            </div>
        </div>
    </div>

    <!--上传附件-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">上传附件</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-upload
            :file-list="filelist" 
            class="upload-demo"
            action="http://localhost:5194/api/PublicFile/Uploadfile"
            multiple
            name="files"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleFileSuccess"
            :headers="headers"
            style="text-align: left;margin-left: 20px;">
            <el-button type="primary">上传附件</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。
                    </div>
                </template>
        </el-upload>
    </div>

    <!-- 底部操作栏 -->
    <div class="action-bar">
        <el-button @click="Close">关闭</el-button>
        <el-button @click="SaveAsDraft">保存为草稿</el-button>
        <el-button type="primary" @click="OK">保存</el-button>
    </div>

    <!--展示货品信息模态框-->
    <el-dialog v-model="dialogTableVisible" title="添加货品" width="800" :close-on-click-modal="false">
        <!-- 动态标题和搜索 -->
        <div v-if="outstockform.type === '销售出库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                销售单号: {{ outstockform.outorder }} | 销售日期: {{ outstockform.date }} | 客户: {{ outstockform.custname }}
            </div>
        </div>
        <div v-if="outstockform.type === '退货出库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                退货单号: {{ outstockform.outorder }}
            </div>
        </div>
        <div v-if="outstockform.type === '调拨出库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                调拨单号: {{ outstockform.outorder }}   | 仓库: {{ outstockform.whname }}
            </div>
        </div>
        <div v-if="outstockform.type === '盘亏出库'">
            <div style="font-weight: bold; margin-bottom: 10px;">
                盘点单号: {{ outstockform.outorder }} | 盘点日期: {{ outstockform.start_time }} | 仓库: {{ outstockform.whname }}
            </div>
        </div>
        <div>
            <el-form :model="procform" ref="procref" :inline="true" style="text-align: left;">
                <el-form-item label="货品名称" prop="name">
                    <el-input placeholder="请输入货品名称" v-model="procform.name"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-select placeholder="请选择单位" v-model="procform.unit" style="width: 200px;">
                        <el-option v-for="item in units" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="Reset">重置</el-button>
                    <el-button type="success" @click="Search">查询</el-button>
                </el-form-item>
            </el-form>
            <!--表格: 销售出库-->
            <el-table v-if="outstockform.type === '销售出库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="proc_saled_price" label="销售单价" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_saled_price ? Number(scope.row.proc_saled_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="proc_saled_num" label="销售数量" width="100"></el-table-column>
                <el-table-column prop="proc_saled_total" label="销售金额" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_saled_total ? Number(scope.row.proc_saled_total).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="saled_outstockOK_num" label="已出库" width="100"></el-table-column>
                <el-table-column label="未出库" width="100">
                    <template #default="scope">
                        {{ scope.row.proc_saled_num - scope.row.saled_outstockOK_num }}
                    </template>
                </el-table-column>
            </el-table>

            <!--表格: 采购退货-->
            <el-table v-if="outstockform.type === '退货出库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="purtd_num" label="退货数量" width="100"></el-table-column>
                <el-table-column prop="purtd_total" label="退货金额" width="100">
                    <template #default="scope">
                        {{ scope.row.purtd_total ? Number(scope.row.purtd_total).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="purtd_outstockOK_num" label="已出库" width="100"></el-table-column>
                <el-table-column label="未出库" width="100">
                    <template #default="scope">
                        {{ scope.row.purtd_num - scope.row.purtd_outstockOK_num }}
                    </template>
                </el-table-column>
            </el-table>


            <!--表格: 调拨出库-->
             <el-table v-if="outstockform.type === '调拨出库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column fixed type="selection" width="50" :selectable="isSelectable"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="150"></el-table-column>
                <el-table-column fixed prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="ald_price" label="调拨单价" width="100">
                    <template #default="scope">
                        {{ scope.row.ald_price ? Number(scope.row.ald_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="ald_num" label="调拨数量" width="100"></el-table-column>
                <el-table-column prop="ald_total" label="调拨金额" width="100">
                    <template #default="scope">
                        {{ scope.row.ald_total ? Number(scope.row.ald_total).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="ald_outstockOK_num" label="已出库" width="100"></el-table-column>
                <el-table-column prop="ald_outstockNO_num" label="未出库" width="100"></el-table-column>
            </el-table>

            <!--表格: 盘亏出库-->
            <el-table v-if="outstockform.type === '盘亏出库'" :data="procdata" stripe height="400" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
                <el-table-column fixed type="selection" width="50"></el-table-column>
                <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
                <el-table-column fixed prop="proc_code" label="货品编号" width="200"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="200"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="200"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="150"></el-table-column>
                <el-table-column prop="icd_price" label="盘点单价" width="120">
                    <template #default="scope">
                        {{ scope.row.icd_price ? Number(scope.row.icd_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="icd_num" label="盘点数量" width="120"></el-table-column>
                <el-table-column prop="profitandloss_num" label="盘亏数量" width="120" fixed="right">
                    <template #default="scope">
                        <span style="color: red;">{{ scope.row.profitandloss_num }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="profitandloss_total" label="盘亏金额" width="120" fixed="right">
                    <template #default="scope">
                        <span style="color: red;">{{ scope.row.profitandloss_total ? Number(scope.row.profitandloss_total).toFixed(2) : '0.00' }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <div style="display: flex; justify-content: flex-end; margin-top: 15px;">
                 <!-- 页码 -->
                <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
                    v-on:current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="success" @click="confirmProductSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>


    <!--单据模态框-->
    <el-dialog v-model="OrderDialog" :title="orderDialogTitle" width="800" :close-on-click-modal="false">
        <!--销售单据-->
        <el-table v-if="outstockform.type === '销售出库'" :data="orderData" stripe border height="400" @selection-change="selectOrder">
            <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
            <el-table-column type="index" label="序号" width="70"></el-table-column>
            <el-table-column prop="sale_code" label="销售单号" width="200"></el-table-column>
            <el-table-column prop="sale_status" label="单据状态" width="120"></el-table-column>
            <el-table-column prop="sale_date" label="销售日期" width="200"></el-table-column>
            <el-table-column prop="cust_name" label="客户名称" width="150"></el-table-column>
            <el-table-column prop="sale_depName" label="销售部门" width="150"></el-table-column>
            <el-table-column prop="cust_linkman" label="收货人" width="150"></el-table-column>
            <el-table-column prop="sale_num" label="货品数量" width="150"></el-table-column>
            <el-table-column prop="sale_total" label="销售金额" width="150"></el-table-column>
        </el-table>

        <!--退货单据-->
        <el-table v-if="outstockform.type === '退货出库'" :data="orderData" stripe height="400" border @selection-change="selectOrder">
            <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
            <el-table-column type="index" label="序号" width="150"></el-table-column>
            <el-table-column prop="purt_code" label="采购单号" width="220"></el-table-column>
            <el-table-column prop="purt_status" label="单据状态" width="150"></el-table-column>
            <el-table-column prop="sup_name" label="供应商" width="150"></el-table-column>
            <el-table-column prop="pur_userName" label="采购人" width="150"></el-table-column>
            <el-table-column prop="pur_depName" label="采购部门" width="150"></el-table-column>
            <el-table-column prop="purt_num" label="退货数量" width="150"></el-table-column>
            <el-table-column prop="purt_total" label="退货金额" width="150"></el-table-column>
        </el-table>

        <!--调拨单据-->
        <el-table v-if="outstockform.type === '调拨出库'" :data="orderData" stripe height="400" border @selection-change="selectOrder">
            <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
            <el-table-column type="index" label="序号" width="150"></el-table-column>
            <el-table-column prop="al_code" label="调拨单号" width="200"></el-table-column>
            <el-table-column prop="al_date" label="调拨申请日" width="200"></el-table-column>
            <el-table-column prop="al_type" label="调拨类型" width="150"></el-table-column>
            <el-table-column prop="out_wh_name" label="调出仓库" width="150"></el-table-column>
            <el-table-column prop="al_num" label="调拨数量" width="150"></el-table-column>
            <el-table-column prop="al_total" label="调拨金额" width="150">
                <template #default="scope">
                    {{ scope.row.al_total ? Number(scope.row.al_total).toFixed(2) : '0.00' }}
                </template>
            </el-table-column>
            <el-table-column prop="approver_name" label="制单人" width="150"></el-table-column>
            <el-table-column prop="approver_time" label="制单时间" width="150"></el-table-column>
        </el-table>

         <!--盘盈单据-->
         <el-table v-if="outstockform.type === '盘亏出库'" :data="orderData" stripe height="400" border @selection-change="selectOrder">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column type="index" label="序号" width="70"></el-table-column>
            <el-table-column prop="ic_code" label="盘点单号" width="200"></el-table-column>
            <el-table-column prop="start_time" label="盘点开始时间" width="200"></el-table-column>
            <el-table-column prop="end_time" label="盘点结束时间" width="200"></el-table-column>
            <el-table-column prop="wh_name" label="盘点仓库" width="150"></el-table-column>
            <el-table-column prop="ic_type" label="盘点类型" width="120"></el-table-column>
            <el-table-column prop="check_num" label="盘点数量" width="120"></el-table-column>
            <el-table-column prop="checklosses_num" label="盘亏数量" width="120">
                <template #default="scope">
                    <span style="color: red;">{{ scope.row.checklosses_num }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="checklosses_total" label="盘亏金额" width="120">
                <template #default="scope">
                    <span style="color: red;">{{ scope.row.checklosses_total ? Number(scope.row.checklosses_total).toFixed(2) : '0.00' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="create_name" label="制单人" width="120"></el-table-column>
            <el-table-column prop="create_time" label="制单时间" width="200"></el-table-column>
        </el-table>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="OrderDialog = false">取消</el-button>
                <el-button type="success" @click="confirmOrder">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script>
import {ref,reactive,onMounted, computed, watch} from 'vue';
import http from '../auth/index';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

export default {
    setup(){
        const router = useRouter();
        const route = useRoute();
        const user = JSON.parse(sessionStorage.getItem("user"));
        //传过来的id和code
        const outstockid = route.params.outstockid;
        const outstockcode = route.params.outstockcode;

        // 表单和校验规则
        const outstockref = ref(null);
        const outstockform = reactive({
            id: "",//单据id
            code: "",
            type: "",
            whid: "",
            whname: "",
            date: new Date(),
            outorder: "",
            sup: "",
            supname:"",
            cust:"",
            custname:"",
            linkman: "",
            linkphone: "",
            outuser: "",
            remark: "",
            status: "",//单据状态
        });
        const rules = reactive({
            type: [{ required: true, message: '请选择出库类型', trigger: 'blur' }],
            whid: [{ required: true, message: '请选择仓库名称', trigger: 'blur' }],
            date: [{ required: true, message: '请选择出库日期', trigger: 'blur' }],
            outuser: [{ required: true, message: '请选择经办人', trigger: 'blur' }],
            outorder: [{ required: true, message: '请选择关联单号', trigger: 'blur' }],
        });

         //日期转换格式
         function formatDateTime(date) {
            if (!date) return '';
            const d = new Date(date);
            if (isNaN(d.getTime())) return '';
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            const hours = String(d.getHours()).padStart(2, '0');
            const minutes = String(d.getMinutes()).padStart(2, '0');
            const seconds = String(d.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

         // 下拉框数据
        const types = ref([]);
        const warehouse = ref([]);
        const users = ref([]);
        const slots = ref([]); // 库位

        // 获取下拉框数据
        const GetTypes = () => http.get("/BusinessType/GetBusinessTypes?field=出库").then(res => types.value = res.data);
        const GetWarehouses = () => http.get("/Warehouse/GetWarehouses").then(res => warehouse.value = res.data);
        const GetUsers = () => http.get("/User/GetAllUser").then(res => users.value = res.data);
        const GetSlots = (whid) => {
            if (!whid) {
                slots.value = [];
                return;
            }
            http.get(`/Slot/GetSlotsByWhid?whid=${whid}`).then(res => {
                slots.value = res.data;
            }).catch(() => {
                slots.value = [];
            });
        }
        //查询所有单据状态
        const status=ref([]);
        function GetStatus(){
            return http.get("/DictData/GetAllDictDataBytype?typeid=6")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }
         // 状态映射计算属性
         const statusMap = computed(() => {
            const map = {};
            if (status.value && status.value.length > 0) {
                status.value.forEach(item => {
                    map[item.dict_value] = item.dict_label;
                });
            }
            return map;
        });

        
        // 计算销售总额
        const calculateAmount = (row) => {
            row.proc_sale_total = (row.proc_sale_num || 0) * (row.proc_sale_price || 0);
        };

        //#region 合计行计算
        const sumNotInstockNum = computed(() => {
            const type = outstockform.type;
            return selectedProducts.value.reduce((sum, item) => {
                let num = 0;
                if (type === '销售出库') {
                    num = (item.proc_saled_num || 0) - (item.saled_outstockOK_num || 0) - (item.outd_num || 0);
                } else if (type === '退货出库') {
                    num = (item.purtd_num || 0) - (item.purtd_outstockOK_num || 0) - (item.outd_num || 0);
                } else if (type === '调拨出库') {
                    num = (item.ald_num || 0) - (item.ald_outOK_num || 0) - (item.outd_num || 0);
                }
                return sum + num;
            }, 0);
        });

        const sumAlreadyInstockNum = computed(() => {
            const type = outstockform.type;
            return selectedProducts.value.reduce((sum, item) => {
                let num = 0;
                if (type === '销售出库') {
                    num = (item.saled_outstockOK_num || 0) + (item.outd_num || 0);
                } else if (type === '退货出库') {
                    num = (item.purtd_outstockOK_num || 0) + (item.outd_num || 0);
                } else if (type === '调拨出库') {
                    num = (item.ald_outOK_num || 0) + (item.outd_num || 0);
                }
                return sum + num;
            }, 0);
        });

        const sumOutstockNum = computed(() => {
            return selectedProducts.value.reduce((sum, item) => sum + (item.outd_num || 0), 0);
        });

        const sumOutstockAmount = computed(() => {
            const type = outstockform.type;
            const total = selectedProducts.value.reduce((sum, item) => {
                let price = 0;
                if (type === '销售出库') {
                    price = item.proc_saled_price || 0;
                } else if (type === '退货出库') {
                    price = item.purtd_price || 0;
                } else if (type === '调拨出库') {
                    price = item.ald_price || 0;
                } else if (type === '盘亏出库') {
                    price = item.outd_price || 0;
                }
                return sum + (item.outd_num || 0) * price;
            }, 0);
            return total.toFixed(2);
        });
        //#endregion


        //获取单位
        function Getunit(){
            http.get("/DictData/GetAllDictDataBytype?typeid=8")
            .then(res => units.value = res.data);
        }


        //#region 获取单据
        const OrderDialog = ref(false);
        const orderData = ref([]);

        const orderDialogTitle = computed(() => {
            const type = outstockform.type;
            if (type === '销售出库') return '选择销售单';
            if (type === '退货出库') return '选择采购退货单';
            if (type === '调拨出库') return '选择调拨单';
            if (type === '盘亏出库') return '选择盘点单';
            return '选择单据';
        });
        
        function openOrderDialog(){
            OrderDialog.value = true;
            GetOrder();
        }
        async function GetOrder(){
            const type = outstockform.type;
            if (!type) {
                ElMessage.warning("请先选择出库类型");
                return;
            }

            let url = "";

            if (type === '销售出库') {
                url = `/Sale_h/GetSale_Hs`;
            } else if (type === '退货出库') {
                url = `/PurchaseReturn_h/GetAllPurchaseReturn_h`;
            } else if (type === '调拨出库') {
                 url = `/Allot_h/GetAllot_Hs?name=outstock_status`;
            } else if (type === '盘亏出库') {
                url = `/Check_h/Getkui`; // 获取有盘亏的盘点单
            }

            if (!url) {
                ElMessage.warning("该出库类型暂未实现");
                return;
            }

            try {
                const res = await http.get(url);
                if (type === '销售出库') {
                    orderData.value = res.data
                    .filter(item => item.sale_status !== 6) // 过滤条件
                    .map(item => ({
                        ...item,
                        sale_date: formatDateTime(new Date(item.sale_date)),
                        sale_total: (item.sale_total || 0).toFixed(2), // 添加默认值
                        sale_status: statusMap.value[item.sale_status] || "未知状态",
                    }));
                } else if (type === '退货出库') {
                    orderData.value = res.data.map(item => ({
                        ...item,
                        purt_date: formatDateTime(new Date(item.purt_date)),
                        purt_total: (item.purt_total || 0).toFixed(2), // 添加默认值
                        purt_status: statusMap.value[item.purt_status] || "未知状态",
                    }));
                } else if (type === '盘亏出库') {
                    orderData.value = res.data.map(item => ({
                        ...item,
                        start_time: formatDateTime(new Date(item.start_time)),
                        end_time: formatDateTime(new Date(item.end_time)),
                        create_time: formatDateTime(new Date(item.create_time)),
                    }));
                } else if(type === '调拨出库'){
                    orderData.value = res.data.map(item => ({
                        ...item,
                        al_date: formatDateTime(new Date(item.al_date)),
                        approver_time: formatDateTime(new Date(item.approver_time)),
                    }));
                } else {
                    orderData.value = res.data;
                }
            } catch (error) {
                console.log(error);
                ElMessage.error("获取单据列表失败");
                orderData.value = [];
            }
        }

        //------------------
        //选中的单据
        const selectedOrders = ref([]);
        function selectOrder(val){
            selectedOrders.value = val;
        }

        async function confirmOrder(){
            if(selectedOrders.value.length === 0){
                ElMessage.warning("请先选择关联单号");
                return;
            }
            const selected = selectedOrders.value[0];
            const type = outstockform.type;

            if (type === '销售出库') {
                outstockform.id = selected.sale_id;
                outstockform.outorder = selected.sale_code;
                outstockform.cust = selected.cust_id;
                outstockform.custname = selected.cust_name;
                outstockform.linkman = selected.cust_linkman;
                outstockform.linkphone = selected.cust_linkphone;
                outstockform.status = selected.sale_status || "";
            } else if (type === '退货出库') {
                outstockform.id = selected.purt_id;
                outstockform.outorder = selected.purt_code;
                outstockform.sup = selected.sup_id;
                outstockform.supname = selected.sup_name;
                outstockform.linkman = selected.sup_linkman;
                outstockform.linkphone = selected.sup_linkphone;
                outstockform.status = selected.purt_status || "";
            } else if (type === '盘亏出库') {
                outstockform.outorder = selected.ic_code;
                outstockform.id = selected.ic_id;
                
                // 盘亏出库：设置仓库并禁用仓库选择
                if (selected.wh_id) {
                    outstockform.whid = selected.wh_id;
                    outstockform.whname = selected.wh_name;
                    
                    // 检查仓库是否锁定
                    try {
                        const warehouseRes = await http.get(`/Warehouse/GetIdWarehouse?id=${selected.wh_id}`);
                        if (warehouseRes.data && warehouseRes.data.is_lock === 1) {
                            ElMessage.error(`盘点单关联的仓库 ${selected.wh_name} 已被锁定，不能用于出库操作！`);
                            return;
                        }
                    } catch (error) {
                        console.error("获取仓库状态失败:", error);
                        ElMessage.warning("无法验证仓库状态，请稍后再试");
                    }
                }
            }else if(type==="调拨出库"){
                outstockform.id = selected.al_id;
                outstockform.outorder = selected.al_code;
                outstockform.whid = selected.out_wh_id;
                outstockform.whname = selected.out_wh_name;
            }
            
            OrderDialog.value = false;
        }
        //#endregion


        //#region 获取货品
        // 添加货品弹窗
        const procform = reactive({ name: "", unit: "" });
        const procref = ref(null);
        const procdata = ref([]);
        const rows = ref(0);
        const currentPage = ref(1);
        const units = ref([]);
        const dialogTableVisible = ref(false);
        function ShowProduct(){
            const type = outstockform.type;
            const associatedOrderTypes = ['销售出库', '退货出库', '调拨出库', '盘亏出库'];

            // 如果是需要关联单据的类型，但尚未选择单据
            if (associatedOrderTypes.includes(type) && !outstockform.outorder) {
                ElMessage.warning("请先选择关联单据后再添加货品！");
                return;
            }

            dialogTableVisible.value = true;
            All();
        }
        async function All(){
            const type = outstockform.type;
            //关联单据id
            const orderId = outstockform.id;

            if (!type) {
                ElMessage.warning("请先选择出库类型");
                return;
            }

            const associatedOrderTypes = ['销售出库', '退货出库', '调拨出库', '盘亏出库'];
            const isAssociatedOrder = associatedOrderTypes.includes(type);

            let url = "";
            let requestConfig = {};

            // 1. 根据出库类型，准备URL和请求参数
            if (isAssociatedOrder) {
                if (type === '销售出库') {
                    url = `/Sale_d/GetSale_ds?saleid=${orderId}`;
                } else if (type === '退货出库') {
                    url = `/PurchaseReturn_d/GetPurchaseReturn_Ds?purtId=${orderId}`;
                } else if (type === '盘亏出库') {
                    url = `/Check_d/GetCheck_DsYingKui?icid=${orderId}&status=盘亏`;
                }else if (type === '调拨出库') {
                    url = `/Allot_d/GetAllot_d?id=${orderId}`;
                }
            }

            // 2. 执行数据获取和处理
            try {
                const res = await http.get(url, requestConfig);
                const initialDetails = res.data.list || res.data;
                console.log(initialDetails);
                // 2.1 如果是关联单据，执行"两步走"数据合并
                if (isAssociatedOrder) {
                    if (!initialDetails || initialDetails.length === 0) {
                        procdata.value = [];
                        rows.value = 0;
                        return ElMessage.info("此单据没有可供选择的货品。");
                    }
                    
                    const productInfoPromises = initialDetails.map(item => 
                        http.get(`/Product/GetProductById?id=${item.proc_id}`)
                    );
                    const productInfoResponses = await Promise.all(productInfoPromises);
                    const fullProductInfos = productInfoResponses.map(res => res.data);

                    const combinedProducts = initialDetails.map(orderItem => {
                        const fullProductInfo = fullProductInfos.find(p => p.proc_id === orderItem.proc_id);
                        return {
                            ...orderItem,
                            proc_code: fullProductInfo ? fullProductInfo.proc_code : 'N/A',
                            proc_model: fullProductInfo ? fullProductInfo.proc_model : 'N/A',
                            proc_primary_unit: fullProductInfo ? fullProductInfo.proc_primary_unit : 'N/A',
                            type_name: fullProductInfo ? fullProductInfo.type_name : 'N/A',
                            proc_inventory: fullProductInfo ? fullProductInfo.proc_inventory : 'N/A',
                        };
                    });

                    // 增加一个健壮的过滤步骤，确保在计算时处理 null 或 undefined 的情况
                    let filteredProducts = combinedProducts;
                    if (type === '销售出库') {
                        filteredProducts = combinedProducts.filter(p => ((p.proc_saled_num || 0) - (p.saled_outstockOK_num || 0)) > 0);
                    } else if (type === '退货出库') {
                        filteredProducts = combinedProducts.filter(p => ((p.purtd_num || 0) - (p.purtd_outstockOK_num || 0)) > 0);
                    }

                    procdata.value = filteredProducts;
                } else {
                // 2.2 如果是直接查询，直接赋值
                    procdata.value = initialDetails;
                    rows.value = res.data.rows || 0;
                }
            } catch (error) {
                ElMessage.error("获取货品数据失败");
                procdata.value = [];
                rows.value = 0;
            }
        }

        //改变页数
        function handlePageChange(page){
            currentPage.value = page;
            All();
        };

        //重置
        function Reset(){
            procref.value?.resetFields();
        }
        //搜索
        function Search(){
            All();
        }
        //是否可选择
        function isSelectable(row){
            return true;
        }
        //表格行样式
        function tableRowClassName(){
            return '';
        }

        //#endregion
        
        
        //#region 确认选择货品
        const multipleSelection = ref([]);
         //选中的产品
        function handleSelectionChange(selection){
            multipleSelection.value = selection;
        }

        function confirmProductSelection(){
             if (multipleSelection.value.length === 0) {
                 ElMessage.warning('请至少选择一个产品');
                 return;
             }
 
             multipleSelection.value.forEach(item => {
                 const existingIndex = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
                 
                 if(existingIndex === -1) {
                     const newItem = {
                         ...item,
                         proc_inventory: item.proc_inventory||0,
                         proc_pur_price: (item.proc_pur_price || 0).toFixed(2),
                         proc_pur_total: (item.proc_pur_total || 0).toFixed(2),
                         proc_saled_price: (item.proc_saled_price || 0).toFixed(2),
                         proc_saled_total: (item.proc_saled_total || 0).toFixed(2),
                         proc_instock_price: (item.proc_instock_price || 0).toFixed(2),
                         proc_instock_total: (item.proc_instock_total || 0).toFixed(2),
                         purtd_price: (item.purtd_price || 0).toFixed(2),
                         purtd_total: (item.purtd_total || 0).toFixed(2),
                       };
                       selectedProducts.value.push(newItem);
                 }
             });
             dialogTableVisible.value = false;
        };

         // 明细表格
        const selectedProducts = ref([]);
        const selectdata = ref([]);
        const SelectChange = (val) => selectdata.value = val;

        //移除货品
        function removeProduct(procId) {
            const index = selectedProducts.value.findIndex(item => item.proc_id === procId);
            if (index !== -1) {
                selectedProducts.value.splice(index, 1);
            }
        };

        //批量移除货品
        function batchRemoveProducts() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请先选择要移除的货品');
                return;
            }
            selectdata.value.forEach(item => {
                const index = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
                if (index !== -1) {
                    selectedProducts.value.splice(index, 1);
                }
            });
            ElMessage.success(`已移除${selectdata.value.length}个货品`);
        };
        //#endregion
         

        //#region 附件
        const filelist = ref([])
        //头部带token
        const token=sessionStorage.getItem('token');
        const headers = {
             Authorization: `Bearer ${token}`, // 添加 token 到请求头
        };
        // 上传成功回调方法
        function handleFileSuccess(response, file, fileList) {
            if (Array.isArray(response)) {
                // 创建 { 文件名: URL } 的映射
                const urlMap = response.reduce((map, res) => {
                    if (res.success) map[res.originalName] = res.path;
                    return map;
                }, {});
                
                // 更新文件列表
                filelist.value = fileList.map(item => ({
                    ...item,
                    url: urlMap[item.name] || item.url,  // 优先使用新URL
                    status: urlMap[item.name] ? 'success' : item.status,
                    originalName: item.originalName || item.name
                }));
            }
        }
        //预览
        function handlePreview(file){
            if (!file.url) {
                ElMessage.error('文件URL不存在，请重新上传');
                return;
            }
            const ext = file.name.split('.').pop().toLowerCase();
            
            switch (ext) {
                case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                    window.open(file.url, '_blank');
                    break;
                case 'pdf':
                    window.open(file.url, '_blank');
                    break;
                case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx':
                    window.open(file.url, '_blank');
                    break;
                default:
                    // 下载其他格式文件
                    const link = document.createElement('a');
                    link.href = file.url;
                    link.download = file.name;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
            }
        };

        //移除附件
        function handleRemove(file, fileList) {
            filelist.value = fileList;
        }
        //#endregion

        // 其他按钮
        const setWarehouse = () => router.push('/main/warehouseadd');

        // 监视仓库ID的变化，以动态获取库位
        watch(() => outstockform.whid, (newWhId) => {
            // 清空明细表中的库位选择
            selectedProducts.value.forEach(product => {
                product.slot_id = null; 
            });
            // 根据新仓库ID获取库位列表
            GetSlots(newWhId);
        });

        //根据类型和单号加载关联单据信息，以获取其ID
        async function loadAssociatedOrder(type, orderCode) {
            if (!type || !orderCode) return;

            let url = "";
            let order;

            try {
                if (type === '销售出库') {
                    url = `/Sale_h/GetSale_Hs`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.sale_code === orderCode);
                    if (order) {
                        outstockform.id = order.sale_id; // 设置关联单据ID
                        outstockform.status = statusMap.value[order.sale_status] || "未知状态"; // 设置状态
                    }
                } else if (type === '退货出库') {
                    url = `/PurchaseReturn_h/GetAllPurchaseReturn_h`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.purt_code === orderCode);
                    if (order) {
                        outstockform.id = order.purt_id; // 设置退货单ID

                        // 关键改动：获取并设置关联的【采购单】的状态
                        if (order.pur_id) {
                            try {
                                const purRes = await http.get(`/Purchase_h/GetPurchase_HById?id=${order.pur_id}`);
                                outstockform.status = statusMap.value[purRes.data.pur_status] || "未知状态";
                            } catch (error) {
                                ElMessage.error("获取关联的采购单状态失败！");
                                outstockform.status = "未知状态";
                            }
                        } else {
                            ElMessage.warning("此退货单未关联到采购单，无法判断入库状态。");
                            outstockform.status = "未知";
                        }
                    }
                } else if (type === '盘亏出库') {
                    url = `/Check_h/Getkui`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.ic_code === orderCode);
                    if (order) {
                        outstockform.id = order.ic_id;
                        outstockform.whid = order.wh_id;
                        outstockform.whname = order.wh_name;
                    }
                }else if(type==='调拨出库'){ 
                    url = `/Allot_h/GetAllot_Hs?name=outstock_status`;
                    const res = await http.get(url);
                    order = res.data.find(o => o.al_code === orderCode);
                    if (order) {
                        outstockform.id = order.al_id; // 设置调拨单ID
                    }
                }
            } catch (error) {
                console.error(`获取${type}关联单据失败:`, error);
            }
        }


        //获取单据及单据明细数据
        async function getOutstockData(){
            try{
                //1.获取出库单主表数据
                const h_res = await http.get(`/Outstock_h/GetOutstock_HById?outstockid=${outstockid}`);
                const data = h_res.data;
                outstockform.code = data.out_code;
                outstockform.type = data.out_type
                outstockform.whid = data.wh_id;
                outstockform.whname = data.wh_name;
                outstockform.date = formatDateTime(new Date(data.out_date));
                outstockform.outorder = data.out_order;
                outstockform.sup = data.sup_id;
                outstockform.supname = data.sup_name;
                outstockform.cust = data.cust_id;
                outstockform.custname = data.cust_name;
                outstockform.linkman = data.linkman;
                outstockform.linkphone = data.linkphone;
                outstockform.outuser = data.out_user;
                outstockform.remark = data.remark;

                 // 2. 根据主表信息，加载关联单据ID和状态
                if (outstockform.outorder) {
                    await loadAssociatedOrder(outstockform.type, outstockform.outorder);
                }

                // 3.获取出库单明细数据
                const d_res = await http.get(`/Outstock_d/GetOutstock_Ds?outstockid=${outstockid}`);
                const outstockDetails = d_res.data;

                if (!outstockDetails || outstockDetails.length === 0) {
                    selectedProducts.value = [];
                    return;
                }

                // 4. 数据扩充：聚合货品信息和源单据（如销售单）的明细信息
                const productIds = [...new Set(outstockDetails.map(item => item.proc_id))];

                // 并行获取所有货品的完整信息
                const productInfoPromises = productIds.map(id => http.get(`/Product/GetProductById?id=${id}`));
                const productInfoResponses = await Promise.all(productInfoPromises);
                const productInfoMap = new Map(productInfoResponses.map(res => res.data ? [res.data.proc_id, res.data] : null).filter(Boolean));

                // 根据出库类型，获取关联的源单据明细
                let sourceDetailsMap = new Map();
                if (outstockform.type === '销售出库' && outstockform.id) {
                    try {
                        const sale_d_res = await http.get(`/Sale_d/GetSale_ds?saleid=${outstockform.id}`);
                        if (sale_d_res.data && Array.isArray(sale_d_res.data)) {
                             sourceDetailsMap = new Map(sale_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取销售明细失败:", error);
                        ElMessage.warning("获取关联的销售明细失败，部分信息可能不完整。");
                    }
                } else if (outstockform.type === '退货出库' && outstockform.id) {
                    try {
                        const purtd_d_res = await http.get(`/PurchaseReturn_d/GetPurchaseReturn_Ds?purtId=${outstockform.id}`);
                        if (purtd_d_res.data && Array.isArray(purtd_d_res.data)) {
                             sourceDetailsMap = new Map(purtd_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取退货明细失败:", error);
                        ElMessage.warning("获取关联的退货明细失败，部分信息可能不完整。");
                    }
                }else if(outstockform.type === '盘亏出库' && outstockform.id){
                    try {
                        const check_d_res = await http.get(`/Check_d/GetCheck_DsYingKui?icid=${outstockform.id}&status=盘亏`);
                        if (check_d_res.data && Array.isArray(check_d_res.data)) {
                             sourceDetailsMap = new Map(check_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取盘亏明细失败:", error);
                        ElMessage.warning("获取关联的盘亏明细失败，部分信息可能不完整。");
                    }
                }else if(outstockform.type === '调拨出库' && outstockform.id){
                    try {
                        const allot_d_res = await http.get(`/Allot_d/GetAllot_d?id=${outstockform.id}`);
                        if (allot_d_res.data && Array.isArray(allot_d_res.data)) {
                             sourceDetailsMap = new Map(allot_d_res.data.map(item => [item.proc_id, item]));
                        }
                    } catch (error) {
                        console.error("获取调拨明细失败:", error);
                        ElMessage.warning("获取关联的调拨明细失败，部分信息可能不完整。");
                    } 
                }

                // 将出库明细、货品信息、源单据明细三方数据聚合
                const combinedDetails = outstockDetails.map(item => {
                    const productInfo = productInfoMap.get(item.proc_id) || {};
                    const sourceDetail = sourceDetailsMap.get(item.proc_id) || {};
                    
                    return {
                        ...sourceDetail,
                        ...productInfo,
                        ...item,
                        proc_id: item.proc_id // 确保proc_id的正确性
                    };
                });
                
                selectedProducts.value = combinedDetails;

                //加载附件
                http.get("/PublicFile/GetPublicFileBy?type=出库单&code="+outstockcode)
                .then(res=>{
                    filelist.value=res.data.map(item=>{
                        return {
                            name: item.title,
                            url:item.file_name,
                            originalName:item.title
                        }
                    })
                })

            } catch(error) {
                ElMessage.error("加载出库单数据失败，请检查网络或联系管理员");
                console.error(error);
            }
        }


        //修改
        async function Update(status = 2) {
              //1.验证表单
              if (!outstockref.value) return;
              const isValid = await outstockref.value.validate();
              if(!isValid) return false;

             //2.验证货品
              if (selectedProducts.value.length === 0) {
                  ElMessage.warning('请添加要出库的货品！');
                  return false;
              }
              for (const product of selectedProducts.value) {
                  if (!product.slot_id) {
                      ElMessage.warning(`请为货品【${product.proc_name}】选择出库库位！`);
                      return false;
                  }
                  if (!product.outd_num || product.outd_num <= 0) {
                      ElMessage.warning(`请输入货品【${product.proc_name}】的出库数量！`);
                      return false;
                  }
              }

              console.log(outstockform.status);
              if(outstockform.status!='未入库'){
                 //判断货品是否存在库存
                for (const product of selectedProducts.value) {
                    const stock = await http.get(`/Stock/GetStockByCriteria?procid=${product.proc_id}&whid=${outstockform.whid}&slotid=${product.slot_id}`);
                    if (stock.data=="") {
                        ElMessage.warning(`货品【${product.proc_name}】在当前所选仓库/库位中没有库存。`);
                        return false;
                    }
                } 
              }
             
             //3.修改数据
             let outstockdata = {}
             let outstockdetaildata={};
             const filelistdata = filelist.value.map(item => {
                 return {
                     business_type:"出库单",
                     business_code:outstockcode,
                     title: item.originalName,
                     file_name: item.url,
                 }
             })
             //--------------------------------
             if(outstockform.type==='销售出库'){
                 //出库单
                 outstockdata = {
                     out_id: outstockid,
                     wh_id: outstockform.whid,
                     wh_name: warehouse.value.find(item => item.wh_id === outstockform.whid)?.wh_name||'',
                     out_date: formatDateTime(new Date(outstockform.date)),
                     out_order: outstockform.outorder||'',
                     sup_id: outstockform.sup||0,
                     sup_name: outstockform.supname||'',
                     cust_id: outstockform.cust||0,
                     cust_name: outstockform.custname||'',
                     linkman: outstockform.linkman||'',
                     linkphone: outstockform.linkphone||'',
                     out_user:outstockform.outuser,
                     out_categories:selectedProducts.value.length,
                     out_num:sumOutstockNum.value,
                     out_total:sumOutstockAmount.value,
                     out_outstockOK_num:sumAlreadyInstockNum.value,
                     out_outstockNO_num:sumNotInstockNum.value,
                     out_status: status,
                     update_name: user.name,
                     update_time: formatDateTime(new Date()),
                     remark: outstockform.remark,
                 }
                 //出库明细
                 outstockdetaildata = selectedProducts.value.map(item => {
                     const currentOutstockQty = item.outd_num || 0;
                     const originalOutstockOkQty = item.saled_outstockOK_num || 0;
                     return {
                         outd_id: item.outd_id,
                         out_id: outstockid,
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         outd_price: item.proc_saled_price || 0,
                         outd_num: currentOutstockQty,
                         outd_outstockOK_num: originalOutstockOkQty + currentOutstockQty,
                         outd_outstockNO_num: (item.proc_saled_num || 0) - (originalOutstockOkQty + currentOutstockQty),
                         outd_total: currentOutstockQty * (item.proc_saled_price || 0),
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || '',
                     }
                 });
             }else if(outstockform.type==='退货出库'){
                //出库单
                outstockdata = {
                     out_id: outstockid,
                     wh_id: outstockform.whid,
                     wh_name: warehouse.value.find(item => item.wh_id === outstockform.whid)?.wh_name||'',
                     out_date: formatDateTime(new Date(outstockform.date)),
                     out_order: outstockform.outorder||'',
                     sup_id: outstockform.sup||0,
                     sup_name: outstockform.supname||'',
                     cust_id: outstockform.cust||0,
                     cust_name: outstockform.custname||'',
                     linkman: outstockform.linkman||'',
                     linkphone: outstockform.linkphone||'',
                     out_user:outstockform.outuser,
                     out_categories:selectedProducts.value.length,
                     out_num:sumOutstockNum.value,
                     out_total:sumOutstockAmount.value,
                     out_outstockOK_num:sumAlreadyInstockNum.value,
                     out_outstockNO_num:sumNotInstockNum.value,
                     out_status: status,
                     update_name: user.name,
                     update_time: formatDateTime(new Date()),
                     remark: outstockform.remark,
                 }
                 //出库明细
                 outstockdetaildata = selectedProducts.value.map(item => {
                    const currentOutstockQty = item.outd_num || 0;
                    const originalOutstockOkQty = item.purtd_outstockOK_num || 0;
                    return {
                         outd_id: item.outd_id,
                         out_id: outstockid,
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         outd_numtotal: item.purtd_num || 0,
                         outd_price: item.purtd_price || 0,
                         outd_num: currentOutstockQty,
                         outd_outstockOK_num: originalOutstockOkQty + currentOutstockQty,
                         outd_outstockNO_num: (item.purtd_num || 0) - (originalOutstockOkQty + currentOutstockQty),
                         outd_total: currentOutstockQty * (item.purtd_price || 0),
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || '',
                     }
                 });
             }else if(outstockform.type==='盘亏出库'){ 
                //出库单
                outstockdata = {
                     out_id: outstockid,
                     wh_id: outstockform.whid,
                     wh_name: warehouse.value.find(item => item.wh_id === outstockform.whid)?.wh_name||'',
                     out_date: formatDateTime(new Date(outstockform.date)),
                     out_order: outstockform.outorder||'',
                     sup_id: outstockform.sup||0,
                     sup_name: outstockform.supname||'',
                     cust_id: outstockform.cust||0,
                     cust_name: outstockform.custname||'',
                     linkman: outstockform.linkman||'',
                     linkphone: outstockform.linkphone||'',
                     out_user:outstockform.outuser,
                     out_categories:selectedProducts.value.length,//出库种类
                    out_num:sumOutstockNum.value,//出库数量
                    out_total:sumOutstockAmount.value,//出库金额
                    out_outstockOK_num:sumOutstockNum.value,//已出库数量
                    out_outstockNO_num:0,//未出库数量
                    out_status: status,//单据状态
                    create_name: user.name,//出库创建人
                    create_time: formatDateTime(new Date()),//出库创建时间
                    remark: outstockform.remark,//出库备注
                 }
                 //出库明细
                 outstockdetaildata = selectedProducts.value.map(item => {
                    const currentOutstockQty = item.outd_num || 0;
                    return {
                         outd_id: item.outd_id,
                         out_id: outstockid,
                         proc_id: item.proc_id,
                        proc_name: item.proc_name,
                        slot_id: item.slot_id,
                        slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                        outd_numtotal: Math.abs(item.profitandloss_num || 0), // 盘亏总数量（取绝对值）
                        outd_price: item.outd_price || 0, // 使用盘点单价
                        outd_num: currentOutstockQty,
                        outd_outstockOK_num: currentOutstockQty, // 盘亏出库直接等于出库数量
                        outd_outstockNO_num: Math.abs(item.profitandloss_num || 0) - currentOutstockQty, // 剩余未出库数量
                        outd_total: currentOutstockQty * (item.outd_price || 0),
                        proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                        remark: item.remark || '',
                     }
                 });
             }else if(outstockform.type==='调拨出库'){
                //出库单
                outstockdata = {
                     out_id: outstockid,
                     wh_id: outstockform.whid,
                     wh_name: warehouse.value.find(item => item.wh_id === outstockform.whid)?.wh_name||'',
                     out_date: formatDateTime(new Date(outstockform.date)),
                     out_order: outstockform.outorder||'',
                     sup_id: outstockform.sup||0,
                     sup_name: outstockform.supname||'',
                     cust_id: outstockform.cust||0,
                     cust_name: outstockform.custname||'',
                     linkman: outstockform.linkman||'',
                     linkphone: outstockform.linkphone||'',
                     out_user:outstockform.outuser,
                     out_categories:selectedProducts.value.length,
                     out_num:sumOutstockNum.value,
                     out_total:sumOutstockAmount.value,
                     out_outstockOK_num:sumAlreadyInstockNum.value,
                     out_outstockNO_num:sumNotInstockNum.value,
                     out_status: status,
                     update_name: user.name,
                     update_time: formatDateTime(new Date()),
                     remark: outstockform.remark,
                 }
                 //出库明细
                 outstockdetaildata = selectedProducts.value.map(item => {
                    const currentOutstockQty = item.outd_num || 0;
                    const originalOutstockOkQty = item.ald_outOK_num || 0;
                    return {
                         outd_id: item.outd_id,
                         out_id: outstockid,
                         proc_id: item.proc_id,
                         proc_name: item.proc_name,
                         slot_id: item.slot_id,
                         slot_name: slots.value.find(s => s.slot_id === item.slot_id)?.slot_name || '',
                         outd_numtotal: item.ald_num || 0,
                         outd_price: item.ald_price || 0,
                         outd_num: currentOutstockQty,
                         outd_outstockOK_num: originalOutstockOkQty + currentOutstockQty,
                         outd_outstockNO_num: (item.ald_num || 0) - (originalOutstockOkQty + currentOutstockQty),
                         outd_total: currentOutstockQty * (item.ald_price || 0),
                         proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : formatDateTime(new Date()),
                         remark: item.remark || '',
                     }
                 });
             }

             // 将所有数据整合到一个 payload 对象中，用于事务性提交
             let payload = {
                 outstockData: outstockdata,
                 outstockDetails: outstockdetaildata,
                 attachments: filelistdata
             };

             console.log(payload);
             try {
                const res = await http.post("/Outstock_h/UpdateOutstock_h", payload);
                if (res.data > 0) {
                    ElMessage.success("更新成功");
                    return true;
                } else {
                    ElMessage.error("更新失败");
                    return false;
                }
             } catch (err) {
                 console.error("完整错误响应:", err.response?.data || err);
                 ElMessage.error("请求失败，请检查网络或联系管理员。");
                 return false;
             }
        };

        //保存为草稿
        async function SaveAsDraft() {
            const result = await Update(1); // 传入状态 1 表示草稿
            if (result) {
                router.push({ name: 'outstock' });
            }
        }
        
        //保存
        async function OK() {
            const result = await Update(2); // 传入状态 2 表示待审核
            if (result) {
                router.push({ name: 'outstock' });
            }
        }

        //关闭
        function Close(){
            router.back();
        }
        //挂载
        onMounted(()=>{
            GetStatus().then(() => {
                getOutstockData().then(() => {
                    GetTypes();
                    GetWarehouses();
                    GetUsers();
                    Getunit();
                });
            });
        });

        // 添加计算属性来判断仓库选择框是否禁用
        const isWarehouseDisabled = computed(() => {
            return outstockform.type === '盘亏出库' && outstockform.outorder;
        });

        return {
            outstockform, outstockref, rules, types, warehouse, users, slots,
            selectedProducts, selectdata, SelectChange, removeProduct, batchRemoveProducts,
            sumNotInstockNum, sumAlreadyInstockNum, sumOutstockNum, sumOutstockAmount,
            dialogTableVisible, ShowProduct, procform, procref, procdata, rows, currentPage,
            Reset, units, Search, handlePageChange, confirmProductSelection,
            handleSelectionChange, multipleSelection, isSelectable, tableRowClassName,
            filelist, headers, handleFileSuccess, handlePreview, handleRemove,
            Close, setWarehouse,OK,SaveAsDraft,
            calculateAmount,
            OrderDialog, openOrderDialog, orderDialogTitle,orderData,selectedOrders,selectOrder,confirmOrder,
            isWarehouseDisabled
        }
    }
}
</script>
  
<style scoped>
    /* 白色圆角容器 - 核心样式 */
    .white-container {
        background: white;
        border-radius: 12px;
        margin-bottom: 50px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        width: 75%;
    }

    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }

    /* 模态框样式 */
    :deep(.el-dialog__body) {
        padding: 10px 20px;
    }
    
    :deep(.el-dialog__footer) {
        border-top: 1px solid #e6e6e6;
        padding: 10px 0;
    }
    
    :deep(.el-dialog__header) {
        border-bottom: 1px solid #e6e6e6;
    }

    :deep(.el-table .warning-row) {
        background: #fef0f0 !important;
    }

    :deep(.el-table .warning-row > td) {
        background: #fef0f0 !important;
    }
</style>








